<template>
  <div>
    <h1 style="text-align: center; margin-bottom: 20px; color: blue;">车辆信息统计</h1>
    <el-card>

     

      <el-row style="margin-top: 10px;">
        <el-col :span="12">
          <el-card>
            <div id="bar-cars" style="width: 100%; height: 400px; text-align: center;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div id="bar-fees" style="width: 100%; height: 400px; text-align: center;"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row style="margin-top: 10px;">
        <el-col :span="6" :offset="9">
          <span class="tag" style="padding-right: 20px; line-height: 36px;">请选择统计时间：</span>
          <el-select v-model="timeRange" placeholder="请选择时间范围" @change="handleTimeRangeChange">
            <el-option label="日统计" value="day"></el-option>
            <el-option label="周统计" value="week"></el-option>
            <el-option label="月统计" value="month"></el-option>
            <el-option label="季统计" value="quarter"></el-option>
            <el-option label="年统计" value="year"></el-option>
          </el-select>
          <!-- Date picker for day -->
          <el-date-picker
            v-if="timeRange === 'day'"
            v-model="selectedDate"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="onDateChange"
          ></el-date-picker>
          <!-- Custom selectors for week, month, quarter, and year -->
          <el-cascader
            v-if="timeRange !== 'day'"
            v-model="selectedPeriod"
            :options="periodOptions"
            :props="{ expandTrigger: 'hover' }"
            @change="onPeriodChange"
          ></el-cascader>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { listGrecords } from '@/api/system/grecords'; // 确保路径正确
import { listPrecords } from '@/api/system/precords'; // 导入车辆信息API
import moment from 'moment'; // 引入 moment.js 用于日期处理

export default {
  data() {
    return {
      totalPlaces: 200, // 总车位数设为定值 200
      sparePlaces: 0,
      timeRange: 'day', // 默认选中日统计
      selectedDate: '', // 新增属性：用于存储选中的日期
      parkedCarsData: [], // 存储累计停车数的数据
      parkingFeesData: [], // 存储累计停车费用的数据
      pieOption: {
        title: {
          text: '车位统计',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        series: [
          {
            name: '车位情况',
            type: 'pie',
            radius: '50%',
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      },
      barCarsOption: {
        title: {
          text: '累计停车数趋势',
          left: 'center',
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['数量'],
          bottom: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '车辆数量'
        },
        series: [
          {
            name: '数量',
            type: 'line',
            data: [],
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              width: 3
            },
            areaStyle: {
              opacity: 0.3
            }
          }
        ],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        }
      },
      barFeesOption: {
        title: {
          text: '累计停车费用趋势',
          left: 'center',
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['金额'],
          bottom: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '金额（元）'
        },
        series: [
          {
            name: '金额',
            type: 'line',
            data: [],
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              width: 3
            },
            areaStyle: {
              opacity: 0.3
            }
          }
        ],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        }
      },
      selectedPeriod: [], // 新增属性：用于存储选中的期间
      periodOptions: [], // 新增属性：用于存储期间选项

    };
  },

methods: {
    async fetchGarageData() {
      try {
        const response = await listGrecords();
        if (response && response.rows && response.rows.length > 0) {
          console.log('API Response:', response);
          const grecord = response.rows[0];
          this.sparePlaces = grecord.spareplace;

          console.log('Total Places:', this.totalPlaces);
          console.log('Spare Places:', this.sparePlaces);

          this.pieOption.series[0].data = [
            { value: this.sparePlaces, name: '空闲车位' },
            { value: this.totalPlaces - this.sparePlaces, name: '已用车位' },
          ];
          this.showPieChart();
        } else {
          console.error('No data in response:', response);
        }
      } catch (error) {
        console.error('Error fetching garage data:', error);
      }
    },

    async getStatistics() {
      try {
        let startTime, endTime;
        if (this.timeRange === 'day' && this.selectedDate) {
          startTime = moment(this.selectedDate).startOf('day').format('YYYY-MM-DD HH:mm:ss');
          endTime = moment(this.selectedDate).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        } else if (this.timeRange === 'week' && this.selectedPeriod.length > 0) {
          const [year, month] = this.selectedPeriod;
          const startOfMonth = moment(`${year}-${month}`, 'YYYY-M').startOf('month');
          const endOfMonth = moment(`${year}-${month}`, 'YYYY-M').endOf('month');

          // Find the first Monday and last Sunday of the chosen month
          const firstMonday = startOfMonth.isoWeekday(1);
          const lastSunday = endOfMonth.isoWeekday(7);

          // Calculate weeks in the chosen month
          const weeksInMonth = Math.ceil((lastSunday.diff(firstMonday, 'days') + 1) / 7);

          // Set time range for the entire month
          startTime = firstMonday.format('YYYY-MM-DD HH:mm:ss');
          endTime = lastSunday.format('YYYY-MM-DD HH:mm:ss');
        } else if (this.timeRange === 'week') {
          // 默认只显示本周数据
          startTime = moment().startOf('week').format('YYYY-MM-DD HH:mm:ss');
          endTime = moment().endOf('week').format('YYYY-MM-DD HH:mm:ss');
        } else if (this.selectedPeriod.length > 0) {
          const [year, period] = this.selectedPeriod;
          switch (this.timeRange) {
            case 'month':
              startTime = moment(`${year}-${period}`, 'YYYY-M').startOf('month').format('YYYY-MM-DD HH:mm:ss');
              endTime = moment(`${year}-${period}`, 'YYYY-M').endOf('month').format('YYYY-MM-DD HH:mm:ss');
              break;
            case 'quarter':
              const q = parseInt(period.replace('Q', ''), 10);
              startTime = moment(year, 'YYYY').quarter(q).startOf('quarter').format('YYYY-MM-DD HH:mm:ss');
              endTime = moment(year, 'YYYY').quarter(q).endOf('quarter').format('YYYY-MM-DD HH:mm:ss');
              break;
            case 'year':
              startTime = moment(year, 'YYYY').startOf('year').format('YYYY-MM-DD HH:mm:ss');
              endTime = moment(year, 'YYYY').endOf('year').format('YYYY-MM-DD HH:mm:ss');
              break;
          }
        } else {
          startTime = this.getStartTime(this.timeRange);
          endTime = this.getEndTime(this.timeRange);
        }

        const response = await listPrecords({
          startTime,
          endTime,
        });

        if (response && response.rows) {
          console.log('Parking Data Response:', response);
          this.calculateStatistics(response.rows);
          this.showBarCharts();
        } else {
          console.error('No parking data in response:', response);
        }
      } catch (error) {
        console.error('Error fetching parking data:', error);
      }
    },

     calculateStatistics(data) {
  const parkedCars = {};
  const parkingFees = {};

  data.forEach(record => {
    let key;
    if (this.timeRange === 'day') {
      // 日统计：按小时分组（根据入场时间统计各个时间段的车辆数量及缴费情况）
      // 确保使用正确的入场时间字段，添加日志便于调试
      console.log('Record entry time:', record.entryTime);
      
      // 确保时间解析正确
      let enterTime;
      if (record.entryTime) {
        enterTime = moment(record.entryTime);
      } else {
        console.error('Missing entry time for record:', record);
        // 为了防止错误，使用当前时间的小时，但记录日志
        enterTime = moment();
      }
      
      // 确保时间解析成功
      if (!enterTime.isValid()) {
        console.error('Invalid entry time:', record.entryTime);
        enterTime = moment();
      }
      
      // 正确映射时间段
      const hour = enterTime.hour();
      console.log('Parsed hour:', hour);
      
      // 确保小时在有效范围内
      const validHour = Math.max(0, Math.min(23, hour));
      const periodIndex = Math.floor(validHour / 2);
      key = `${(periodIndex * 2).toString().padStart(2, '0')}:00`;
      console.log('Mapped to period:', key);
    } else if (this.timeRange === 'week') {
      // 周统计：按星期几分组
      const weekInfo = moment(record.entryTime);
      
      if (this.selectedPeriod.length > 0) {
        // 用户选择了具体的年月，按原逻辑处理
        const year = parseInt(this.selectedPeriod[0], 10);
        const month = parseInt(this.selectedPeriod[1], 10);

        // 检查记录是否在选中的月份内
        if (weekInfo.year() === year && weekInfo.month() + 1 === month) {
          const startOfMonth = moment([year, month - 1, 1]);
          const firstMonday = startOfMonth.isoWeekday(1);

          // 确定记录属于该月的第几周
          const weekNumber = Math.ceil((weekInfo.diff(firstMonday, 'days') + 1) / 7);
          
          // 按星期几分组
          const dayOfWeek = weekInfo.day();
          const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
          
          key = `第${weekNumber}周-${weekDays[dayOfWeek]}`;
        } else {
          // 如果记录不在选中的月份内，跳过
          return;
        }
      } else {
        // 默认情况下（显示本周数据），直接按星期几分组
        const dayOfWeek = weekInfo.day();
        const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        
        key = weekDays[dayOfWeek];
      }
    } else if (this.timeRange === 'month') {
      // 月统计：按日期分组
      const [year, month] = this.selectedPeriod;
      const recordDate = moment(record.entryTime);
      
      // 检查记录是否在选中的月份内
      if (recordDate.year() === parseInt(year) && recordDate.month() + 1 === parseInt(month)) {
        key = `${recordDate.date()}日`;
      } else {
        return;
      }
    } else if (this.timeRange === 'quarter') {
      // 季度统计：按月份分组
      const [year, quarter] = this.selectedPeriod;
      const q = parseInt(quarter.replace('Q', ''), 10);
      const recordDate = moment(record.entryTime);
      
      // 检查记录是否在选中的季度内
      if (recordDate.year() === parseInt(year) && recordDate.quarter() === q) {
        const quarterMonths = {
          1: ['1月', '2月', '3月'],
          2: ['4月', '5月', '6月'],
          3: ['7月', '8月', '9月'],
          4: ['10月', '11月', '12月']
        };
        
        key = quarterMonths[q][recordDate.month() - (q - 1) * 3];
      } else {
        return;
      }
    } else if (this.timeRange === 'year') {
      // 年统计：按月份分组
      const year = this.selectedPeriod[0];
      const recordDate = moment(record.entryTime);
      
      // 检查记录是否在选中的年份内
      if (recordDate.year() === parseInt(year)) {
        key = `${recordDate.month() + 1}月`;
      } else {
        return;
      }
    } else {
      key = this.selectedPeriod.join('-'); // 使用用户选择的时间段作为键值
    }

    if (!parkedCars[key]) {
      parkedCars[key] = 0;
    }
    if (!parkingFees[key]) {
      parkingFees[key] = 0;
    }

    parkedCars[key]++;
    parkingFees[key] += record.amount || 0;
  });

  // 针对不同时间范围设置默认的时间点，确保图表显示完整
  const getDefaultTimePoints = () => {
    switch (this.timeRange) {
      case 'day':
        // 一天24小时，每两小时一个点
        return Array.from({length: 12}, (_, i) => `${(i * 2).toString().padStart(2, '0')}:00`);
      case 'week':
        // 一周七天
        return ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      case 'month':
        // 一个月最多31天
        return Array.from({length: 31}, (_, i) => `${i + 1}日`);
      case 'quarter':
        // 一个季度3个月
        const q = parseInt(this.selectedPeriod[1].replace('Q', ''), 10);
        const quarterMonths = {
          1: ['1月', '2月', '3月'],
          2: ['4月', '5月', '6月'],
          3: ['7月', '8月', '9月'],
          4: ['10月', '11月', '12月']
        };
        return quarterMonths[q] || [];
      case 'year':
        // 一年12个月
        return ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
      default:
        return [];
    }
  };

  const defaultTimePoints = getDefaultTimePoints();
  
  // 初始化默认值
  defaultTimePoints.forEach(point => {
    if (!parkedCars[point]) {
      parkedCars[point] = 0;
    }
    if (!parkingFees[point]) {
      parkingFees[point] = 0;
    }
  });

  this.parkedCarsData = Object.entries(parkedCars)
    .sort((a, b) => {
      // 根据时间范围设置排序规则
      if (this.timeRange === 'day') {
        // 按时间排序
        return a[0].localeCompare(b[0]);
      } else if (this.timeRange === 'week') {
        // 按星期几排序
        const weekDayOrder = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        // 修复排序逻辑：同时处理带周数和不带周数的情况
        const getWeekDay = str => {
          // 如果包含'-'，取第二部分；否则直接使用整个字符串
          const parts = str.split('-');
          return parts.length > 1 ? parts[1] : str;
        };
        return weekDayOrder.indexOf(getWeekDay(a[0])) - weekDayOrder.indexOf(getWeekDay(b[0]));
      } else if (this.timeRange === 'month') {
        // 按日期排序
        return parseInt(a[0]) - parseInt(b[0]);
      } else {
        // 默认按字符串排序
        return a[0].localeCompare(b[0]);
      }
    })
    .map(([key, count]) => ({ date: key, count }));

  this.parkingFeesData = Object.entries(parkingFees)
    .sort((a, b) => {
      // 与停车数相同的排序规则
      if (this.timeRange === 'day') {
        return a[0].localeCompare(b[0]);
      } else if (this.timeRange === 'week') {
        const weekDayOrder = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        // 修复排序逻辑：同时处理带周数和不带周数的情况
        const getWeekDay = str => {
          // 如果包含'-'，取第二部分；否则直接使用整个字符串
          const parts = str.split('-');
          return parts.length > 1 ? parts[1] : str;
        };
        return weekDayOrder.indexOf(getWeekDay(a[0])) - weekDayOrder.indexOf(getWeekDay(b[0]));
      } else if (this.timeRange === 'month') {
        return parseInt(a[0]) - parseInt(b[0]);
      } else {
        return a[0].localeCompare(b[0]);
      }
    })
    .map(([key, fee]) => ({ date: key, fee }));

  this.barCarsOption.xAxis.data = this.parkedCarsData.map(item => item.date);
  this.barCarsOption.series[0].data = this.parkedCarsData.map(item => item.count);

  this.barFeesOption.xAxis.data = this.parkingFeesData.map(item => item.date);
  this.barFeesOption.series[0].data = this.parkingFeesData.map(item => item.fee);
},

    getStartTime(timeRange) {
      return moment().startOf(timeRange).format('YYYY-MM-DD HH:mm:ss'); // 根据需要调整时间格式
    },

    getEndTime(timeRange) {
      return moment().endOf(timeRange).format('YYYY-MM-DD HH:mm:ss'); // 根据需要调整时间格式
    },

    showPieChart() {
      let myEchartsPie = echarts.init(document.getElementById("pie"));
      myEchartsPie.setOption(this.pieOption);
    },

     showBarCharts() {
        let myEchartsBarCars = echarts.init(document.getElementById("bar-cars"));
        const barCarsOption = {
          ...this.barCarsOption,
          series: [{
            ...this.barCarsOption.series[0],
            lineStyle: {
              color: '#b3d4fc', // 停车数量的线条颜色
              width: 3
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(179, 212, 252, 0.5)'
                },
                {
                  offset: 1,
                  color: 'rgba(179, 212, 252, 0.1)'
                }
              ])
            },
            itemStyle: {
              color: '#b3d4fc' // 停车数量的点颜色
            }
          }]
        };
        myEchartsBarCars.setOption(barCarsOption);

        let myEchartsBarFees = echarts.init(document.getElementById("bar-fees"));
        const barFeesOption = {
          ...this.barFeesOption,
          series: [{
            ...this.barFeesOption.series[0],
            lineStyle: {
              color: '#ffecb3', // 停车费用的线条颜色
              width: 3
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(255, 236, 179, 0.5)'
                },
                {
                  offset: 1,
                  color: 'rgba(255, 236, 179, 0.1)'
                }
              ])
            },
            itemStyle: {
              color: '#ffecb3' // 停车费用的点颜色
            }
          }]
        };
        myEchartsBarFees.setOption(barFeesOption);
        
        // 添加窗口大小变化时重新调整图表大小的事件监听
        window.addEventListener('resize', () => {
          myEchartsBarCars.resize();
          myEchartsBarFees.resize();
        });
      },

     handleTimeRangeChange(value) {
        this.selectedDate = '';
        this.selectedPeriod = [];
        this.generatePeriodOptions(value);
        // 清空图表
            this.clearCharts();

        // 不再自动选择默认值
        if (value !== 'year' && value !== 'week') {
          if (this.periodOptions.length > 0 && this.periodOptions[0].children?.length > 0) {
            this.selectedPeriod = [this.periodOptions[0].value, this.periodOptions[0].children[0].value];
            this.getStatistics(); // 在非'year'和非'week'范围内刷新统计数据
          }
        } else if (value === 'week') {
          // 对于周统计，不自动选择年月，使用默认的本周数据
          this.getStatistics();
        } else {
          // 如果是'year'，则不立即获取统计数据，等待用户选择具体年份
        }
      },

       clearCharts() {
          // 清空柱状图的数据
          this.barCarsOption.xAxis.data = [];
          this.barCarsOption.series[0].data = [];
          this.barFeesOption.xAxis.data = [];
          this.barFeesOption.series[0].data = [];

          // 重新设置柱状图选项以清除显示内容
          this.showBarCharts();
        },

      onPeriodChange(value) {
        if (value.length > 0) {
          const [year] = value;
          if (this.timeRange === 'year') {
            // 当选择了具体的年份后，获取统计数据
            this.getStatistics();
          } else {
            // 对于其他时间范围（如周、月、季度），继续使用原有的逻辑
            this.selectedPeriod = value;
            this.getStatistics();
          }
        }
      },

     generatePeriodOptions(timeRange) {
       const now = moment();
       let periods = [];

       switch (timeRange) {
         case 'week':
          //  for (let year = now.year(); year >= now.year() - 1; year--) {
          //    // Generate month options for each year without weeks
          //    const months = Array.from({ length: 12 }, (_, i) => ({
          //      value: `${i + 1}`,
          //      label: `第${year}年第${i + 1}月`
          //    }));

          //    periods.push({
          //      value: year,
          //      label: `第${year}年`,
          //      children: months
          //    });
          //  }
           break;

         case 'month':
           for (let year = now.year(); year >= now.year() - 1; year--) {
             const months = Array.from({ length: 12 }, (_, i) => ({
               value: `${i + 1}`,
               label: `第${year}年第${i + 1}月`,
             }));
             periods.push({ value: year, label: `第${year}年`, children: months });
           }
           break;

         case 'quarter':
           for (let year = now.year(); year >= now.year() - 1; year--) {
             const quarters = Array.from({ length: 4 }, (_, i) => ({
               value: `Q${i + 1}`,
               label: `第${year}年第${i + 1}季度`,
             }));
             periods.push({ value: year, label: `第${year}年`, children: quarters });
           }
           break;

         case 'year':
           for (let year = now.year(); year >= now.year() - 5; year--) {
             periods.push({ value: year, label: `第${year}年` });
           }
           break;

         default:
           break;
       }

       this.periodOptions = periods;
     },



    onDateChange(value) {
      if (this.timeRange === 'day' && value) {
        this.getStatistics();
      }
    },
  },
  created() {
    // this.fetchGarageData();
    this.generatePeriodOptions(this.timeRange); // 初始化时生成期间选项
    this.getStatistics(); // 初始化时获取统计数据
  },
};
</script>

<style scoped>
.choose {
  display: flex;
  justify-content: center;
  align-items: center;
}

.graduationChoose {
  padding: 20px;
}

div {
  text-align: center;
  white-space: pre;
}

h1 {
  font-size: 24px;
  color: blue;
}

.tag {
  display: inline-block;
  vertical-align: middle;
}
</style>
